// init tree source data
var treeData = [];
var rows = {};

for(var i=0; i<data.length; i++)
{
    var id = data[i][0];
    var name = data[i][1];
    var parent = data[i][2];
    var checked = data[i][3];

    var row = {key:id, title:name, children: [], parent:parent};
    rows[id] = row;

    // add root
    if (parent == 0)
    {
        row['isFolder'] = true;
        treeData.push(row);
    }
    // add children
    else
        rows[parent]['children'].push(row);
}

function Selector(callback)
{
    var $ = jQuery;

    // main widget
    var body = document.getElementsByTagName('BODY')[0];
    var div = document.createElement('DIV');
    div.className = 'selector';
    body.appendChild(div);

    // tree
    var tree = document.createElement('DIV');
    tree.className = 'tree';
    div.appendChild(tree);

    // out
    var out = document.createElement('DIV');
    out.className = 'out';
    div.appendChild(out);

    // close
    var close = document.createElement('a');
    close.className = 'close';
    div.appendChild(close);
    $(close).bind('click', function(evt) { $(div).remove(); });

    // done
    var done = document.createElement('INPUT');
    done.type = 'button';
    done.value = 'Готово';
    done.className = 'done';
    div.appendChild(done);

    $(done).bind('click', function(evt) {
        // group selected nodes
        var items = {};

        var tree = $(".selector .tree").first().dynatree("getTree");
        var selNodes = tree.getSelectedNodes();

        // group items by parent (one level only)
        $(selNodes).each(function(i, nd) {
            if (nd.data.parent == 0)
                return;

            if (typeof items[nd.data.parent] == 'undefined')
                items[nd.data.parent] = [];

            items[nd.data.parent].push(nd.data);
            });

        // format result
        var result = []; // сфера, специализация, специализация, специализация

        $.each(items, function(i, specs) {
            var row = [rows[i].title];
            $(specs).each(function(i, e) { row.push(e.title); });
            result.push(row);
            });

        callback(result);
        $(div).remove();
        });

    // disable checkboxes
    var disableCheckboxes = function(nd)
    {
        var childs = nd.getChildren();

        // count selected
        var cnt = 0;
        $.each(childs, function (i, e) {
            if (e.isSelected())
                cnt++;
            });

        // disable
        if (cnt > 2)
        {
            $.each(childs, function (i, e) {
                if (!e.isSelected())
                {
                    $(e.li).addClass('disabled');
                    e.data.unselectable = true;
                }
                });
        }
        // reenable
        else
        {
            $.each(childs, function (i, e) {
                $(e.li).removeClass('disabled');
                e.data.unselectable = false;
                });
        }

        return true;
    }


    var renderRightBlock = function(items)
    {
            // render right block (selected items)
            var html = '';
            html += '<div class="title">';
            html += 'Выбрано';
            html += '</div>';
            $.each(items, function(i, childs) {
                html += '<div class="lev-0">';
                html += '<div class="inner">';
                html += rows[i].title;
                html += '<a class="remove" rel="'+rows[i].key+'"></a>';

                $.each(childs, function(i2, e) {
                    html += '<div class="lev-1">';
                    html += '<div class="inner">';
                    html += e.title;
                    html += '<a class="remove" rel="'+e.key+'"></a>';
                    html += '</div>';
                    html += '</div>';
                    });

                html += '</div>';
                html += '</div>';
                });

            // render out
            $('.selector .out').html(html);
    }
    

    // init tree
    $(".selector .tree").dynatree({
        checkbox: true,
        selectMode: 3,
        autoCollapse: true,
        fx: { height: "toggle", duration: 200 },
        children: treeData,
        selectMode: 2,
        onSelect: function(is_selected, node)
        {
            var items = {};
            var selNodes = node.tree.getSelectedNodes();

            // group items by parent (one level only)
            $(selNodes).each(function(i, nd)
            {
                if (nd.data.parent == 0)
                    return;

                if (typeof items[nd.data.parent] == 'undefined')
                    items[nd.data.parent] = [];

                items[nd.data.parent].push(nd.data);
            });

            // remove check from all childs
            if (!is_selected)
            {
                var fn = function(node)
                {
                    node.select(false);
                };
                node.visit(fn, false);
            }

	    renderRightBlock(items);

            // bind event to 'remove'
            var fn = function(evt)
            {
                var key = evt.target.rel;

                var tree = $(".selector .tree").first().dynatree("getTree");
                var node = tree.getNodeByKey(key);
                node.select(false);

                var childs = node.getChildren();
                $.each(childs, function(i, e) {
                    e.select(false);
                    });

                // disable checkboxes
                node.visitParents(disableCheckboxes, true);

                // hide
                delete items[key];
                renderRightBlock(items);

                return false;
            }
            $(out).find('a.remove').bind('click', fn);

            // set checked all parents
            if (is_selected)
            {
                var fn = function(node)
                {
                    node.select(true);
                    return true;
                }
                node.visitParents(fn, false);
            }

            // disable checkboxes
            node.visitParents(disableCheckboxes, false);
        },
        onExpand: function(is_expanded, node)
        {
            node.visitParents(disableCheckboxes, true);
        },
        onClick: function(node, event) {},
        onDblClick: function(node, event) {node.toggleSelect();}
    });

    // center
    var w = $(window);
    $(div).css("position", "absolute");
    $(div).css("top",(w.height()-$(div).height())/2+w.scrollTop() + "px");
    $(div).css("left",(w.width()-$(div).width())/2+w.scrollLeft() + "px");
};
